package com.chromatic.competition.view.profile;

import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.chromatic.competition.R;
import com.chromatic.competition.model.UserAccount;
import com.chromatic.competition.utils.UserLoginStatus;
import com.chromatic.competition.utils.UserManager;

public class MyAccountActivity extends AppCompatActivity {
    private final UserManager userAccountManager = new UserManager();
    private EditText userIdEditText;
    private EditText usernameEditText;
    private EditText phoneNumberEditText;
    private EditText emailEditText;
    private Button editUsernameButton,editTelephoneButton,editEmailButton;
    private boolean isEditModeUsername, isEditModeTelephone, isEditModeEmail = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_account_info);

        // 初始化视图
        userIdEditText = findViewById(R.id.editTextUserID);
        usernameEditText = findViewById(R.id.editTextUsername);
        phoneNumberEditText = findViewById(R.id.editTextPhoneNumber);
        emailEditText = findViewById(R.id.editTextEmail);
        editUsernameButton = findViewById(R.id.editButtonUsername);
        editTelephoneButton = findViewById(R.id.editButtonPhoneNumber);
        editEmailButton = findViewById(R.id.editButtonEmail);

        int userId = new UserLoginStatus(this).getCurrentUserId();
        Log.d("MyAccountActivity的onCreate方法","该用户的用户ID是" + userId);
        getUserAccountInfo(userId);

        // 设置保存按钮的点击事件监听器
        ImageView backButton = findViewById(R.id.backButton);
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed(); // 调用系统返回操作
            }
        });

        // 设置 "Edit" 按钮的点击事件监听器
        editUsernameButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleUsernameEditMode(userId);
            }
        });

        // 设置 "Edit" 按钮的点击事件监听器
        editTelephoneButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleTelephoneEditMode(userId);
            }
        });

        // 设置 "Edit" 按钮的点击事件监听器
        editEmailButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleEmailEditMode(userId);
            }
        });
    }

    private void toggleUsernameEditMode(int userId) {
        isEditModeUsername = !isEditModeUsername;
        if (isEditModeUsername) {
            // 进入编辑模式
            editUsernameButton.setText("保存");
            usernameEditText.setEnabled(true);
        } else {
            // 退出编辑模式
            showConfirmationDialog(userId);
            editUsernameButton.setText("修改");
            usernameEditText.setEnabled(false);
        }
    }

    private void toggleTelephoneEditMode(int userId) {
        isEditModeTelephone = !isEditModeTelephone;
        if (isEditModeTelephone) {
            // 进入编辑模式
            editTelephoneButton.setText("保存");
            phoneNumberEditText.setEnabled(true);

        } else {
            // 退出编辑模式
            showConfirmationDialog(userId);
            editTelephoneButton.setText("更换");
            phoneNumberEditText.setEnabled(false);
        }
    }

    private void toggleEmailEditMode(int userId) {
        isEditModeEmail = !isEditModeEmail;
        if (isEditModeEmail) {
            // 进入编辑模式
            editEmailButton.setText("保存");
            emailEditText.setEnabled(true);
        } else {
            showConfirmationDialog(userId);
            editEmailButton.setText("更换");
            emailEditText.setEnabled(false);
        }
    }

    private void getUserAccountInfo(int userId) {
        // 调用适当的方法从服务器获取用户账户信息，并更新界面上的文本框内容
        userAccountManager.getUserAccount(userId, new UserManager.UserAccountCallback() {
            @Override
            public void onSuccess(UserAccount userAccount) {
                // 获取成功，更新界面上的文本框内容
                userIdEditText.setText(String.valueOf(userAccount.getUserId()));
                usernameEditText.setText(userAccount.getUsername());
                phoneNumberEditText.setText(userAccount.getPhoneNumber());
                emailEditText.setText(userAccount.getEmail());
            }
            @Override
            public void onError(String errorMessage) {
                // 处理获取用户账户信息失败的情况
                Log.d("MyAccountActivity的getUserAccountInfo方法","错误信息：" + errorMessage);
                Toast.makeText(MyAccountActivity.this, "获取用户账户信息失败！", Toast.LENGTH_SHORT).show();
            }
        });
    }


    private void showConfirmationDialog(int userId) {
        // 创建对话框，询问用户是否确认修改
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("确定修改账户信息？")
            .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    saveAccountInfo(userId);
                }
            })
            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // 用户取消保存，不执行任何操作
                }
            })
            .show();
    }

    private void saveAccountInfo(int userId) {
        userAccountManager.getUserAccount(userId, new UserManager.UserAccountCallback(){
            @Override
            public void onSuccess(UserAccount userAccount){
                userAccount.setUsername(usernameEditText.getText().toString().trim());
                userAccount.setPhoneNumber(phoneNumberEditText.getText().toString().trim());
                userAccount.setEmail(emailEditText.getText().toString().trim());

                userAccountManager.updateUserAccount(userId, userAccount, new UserManager.UserAccountCallback() {
                    @Override
                    public void onSuccess(UserAccount userAccount1) {
                        Toast.makeText(MyAccountActivity.this, "账户信息修改成功！", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onError(String errorMessage) {
                        Toast.makeText(MyAccountActivity.this, "账户信息更新出错: " + errorMessage, Toast.LENGTH_LONG).show();
                        Log.d("MyAccountActivity的saveAccountInfo方法","错误信息：" + errorMessage);
                    }
                });
            }
            @Override
            public void onError(String errorMessage) {
                Toast.makeText(MyAccountActivity.this, "获取用户信息失败: " + errorMessage, Toast.LENGTH_LONG).show();
            }
        });
    }
}
